package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MenuDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.pojo.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

@Service
@Slf4j
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;
    @Autowired
    private UserDao userDao;

    @Override
    public List<Menu> findByUsername(String username) {
        log.debug("MenuServiceImpl: findByUsername: username ===> " + username);
        //根据用户名查询用户信息
        SysUser user = userDao.findByUsername(username);
        Set<Role> roles = user.getRoles();
        //定义List集合接收菜单信息
        List<Menu> parentList = new ArrayList<Menu>();
        List<Menu> childMenuList = new ArrayList<>();
        for (Role role : roles) {
            //根据roleId查询菜单信息并返回
            List<Menu> menus = menuDao.findMenuByRoleId(role.getId());
            //遍历集合,获取父菜单
            for (Menu menu : menus) {
                if (menu.getParentMenuId() == null){
                    parentList.add(menu);
                }else {
                    childMenuList.add(menu);
                }
            }
            for (Menu menu : parentList) {
                menu.setChildren(getChildMenuList(menu.getId(),childMenuList));
            }

        }
        //优先级排序
        Collections.sort(parentList, new Comparator<Menu>() {
            @Override
            public int compare(Menu o1, Menu o2) {
                return o1.getPriority()-o2.getPriority();
            }
        });
        for (Menu menu : parentList) {
            Collections.sort(menu.getChildren(), new Comparator<Menu>() {
                @Override
                public int compare(Menu o1, Menu o2) {
                    return o1.getPriority()-o2.getPriority();
                }
            });
        }
        log.debug("MenuServiceImpl: findByUsername: parentList ===> " + parentList);
        return parentList;
    }

    private List<Menu> getChildMenuList(Integer parentId,List<Menu> childMenuList){
        List<Menu> childList = new ArrayList<>();
        for (Menu menu : childMenuList) {
            if (parentId == menu.getParentMenuId()){
                childList.add(menu);
            }
        }
        return childList;
    }

}
